#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
企业舆情分析系统 - 后端API服务
提供REST API接口，支持前端界面操作
"""

import os
import json
import asyncio
import sqlite3
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Any
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
from dataclasses import asdict
import threading
import concurrent.futures

# 导入我们的系统模块
from enterprise_analysis_system import EnterpriseAnalysisSystem, create_analysis_system
from threat_analysis_system import ThreatAnalysisSystem, create_threat_analysis_system
from database_init import DatabaseInitializer
from question_generator import QuestionType

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 全局配置
CONFIG_FILE = "ai_config.json"
DATABASE_PATH = "enterprise_analysis.db"
API_KEYS_FILE = "api_keys.json"

# 全局系统实例
analysis_system = None
threat_system = None

class APIKeyManager:
    """API Key管理器"""
    
    def __init__(self, keys_file: str = API_KEYS_FILE):
        self.keys_file = keys_file
        self.load_keys()
    
    def load_keys(self):
        """加载API Keys"""
        try:
            if os.path.exists(self.keys_file):
                with open(self.keys_file, 'r', encoding='utf-8') as f:
                    self.keys = json.load(f)
            else:
                self.keys = {
                    "baidu": {"api_key": "", "secret_key": "", "enabled": False},
                    "aliyun": {"api_key": "", "enabled": False},
                    "zhipu": {"api_key": "", "enabled": False},
                    "kimi": {"api_key": "", "enabled": False},
                    "deepseek": {"api_key": "", "enabled": False}
                }
                self.save_keys()
        except Exception as e:
            print(f"加载API Keys失败: {e}")
            self.keys = {}
    
    def save_keys(self):
        """保存API Keys"""
        try:
            with open(self.keys_file, 'w', encoding='utf-8') as f:
                json.dump(self.keys, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存API Keys失败: {e}")
    
    def update_key(self, provider: str, key_data: Dict):
        """更新特定提供商的API Key"""
        if provider not in self.keys:
            self.keys[provider] = {}
        self.keys[provider].update(key_data)
        self.save_keys()
    
    def get_enabled_providers(self) -> List[str]:
        """获取已启用的提供商列表"""
        return [provider for provider, config in self.keys.items() 
                if config.get('enabled', False) and config.get('api_key')]
    
    def to_config_format(self) -> Dict:
        """转换为系统配置格式"""
        config = {}
        for provider, keys in self.keys.items():
            if keys.get('enabled', False) and keys.get('api_key'):
                if provider == "baidu":
                    config[provider] = {
                        "api_key": keys['api_key'],
                        "secret_key": keys.get('secret_key', '')
                    }
                else:
                    config[provider] = {
                        "api_key": keys['api_key']
                    }
        return config

# 初始化API Key管理器
api_key_manager = APIKeyManager()

def load_config():
    """加载配置文件"""
    try:
        if os.path.exists(CONFIG_FILE):
            with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        else:
            # 如果配置文件不存在，返回默认配置
            return {
                "system_settings": {
                    "threat_analysis": {
                        "auto_analyze_new_sessions": True
                    }
                }
            }
    except Exception as e:
        print(f"❌ 加载配置文件失败: {e}")
        return {}

def init_systems():
    """初始化分析系统"""
    global analysis_system, threat_system
    try:
        # 检查是否有至少一个启用的提供商
        enabled_providers = api_key_manager.get_enabled_providers()
        if not enabled_providers:
            print("⚠️ 没有启用的AI提供商，使用默认配置初始化系统")
            # 即使没有API Key也尝试初始化系统
        
        # 创建配置文件
        config = api_key_manager.to_config_format()
        
        # 如果没有配置，创建一个空配置文件
        if not config:
            config = {}
        
        with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
            json.dump(config, f, ensure_ascii=False, indent=2)
        
        # 获取DeepSeek API Key
        deepseek_key = api_key_manager.keys.get('deepseek', {}).get('api_key', '')
        
        # 初始化系统（即使没有API Key也要初始化）
        analysis_system = create_analysis_system(CONFIG_FILE, deepseek_key)
        threat_system = create_threat_analysis_system(deepseek_key, DATABASE_PATH)
        
        print(f"✅ 系统初始化成功，已启用提供商: {enabled_providers}")
        return True
    except Exception as e:
        print(f"❌ 系统初始化失败: {e}")
        import traceback
        traceback.print_exc()
        return False

@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查"""
    return jsonify({
        'status': 'healthy',
        'timestamp': datetime.now().isoformat(),
        'systems': {
            'analysis': analysis_system is not None,
            'threat': threat_system is not None
        }
    })

@app.route('/api/config/providers', methods=['GET'])
def get_providers():
    """获取AI提供商配置"""
    return jsonify({
        'providers': api_key_manager.keys,
        'enabled_count': len(api_key_manager.get_enabled_providers())
    })

@app.route('/api/config/providers/<provider>', methods=['PUT'])
def update_provider(provider):
    """更新AI提供商配置"""
    try:
        data = request.get_json()
        api_key_manager.update_key(provider, data)
        
        # 重新初始化系统
        success = init_systems()
        
        return jsonify({
            'success': True,
            'message': f'{provider} 配置已更新',
            'system_initialized': success
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400

@app.route('/api/analysis/enterprise', methods=['POST'])
def analyze_enterprise():
    """启动企业分析"""
    try:
        if not analysis_system:
            # 尝试重新初始化系统
            init_result = init_systems()
            if not init_result or not analysis_system:
                return jsonify({
                    'success': False, 
                    'error': '分析系统未初始化，请检查AI提供商配置',
                    'suggestion': '请在"系统配置"页面配置至少一个AI服务的API Key'
                }), 500
        
        data = request.get_json()
        enterprise_name = data.get('enterprise_name', '').strip()
        if not enterprise_name:
            return jsonify({'success': False, 'error': '企业名称不能为空'}), 400
        
        # 解析问题类型
        question_types = []
        type_mapping = {
            'negative_news': QuestionType.NEGATIVE_NEWS,
            'positive_news': QuestionType.POSITIVE_NEWS,
            'financial_info': QuestionType.FINANCIAL_INFO,
            'market_analysis': QuestionType.MARKET_ANALYSIS,
            'product_info': QuestionType.PRODUCT_INFO,
            'leadership': QuestionType.LEADERSHIP,
            'competitive_analysis': QuestionType.COMPETITIVE_ANALYSIS,
            'technology': QuestionType.TECHNOLOGY,
            'reputation': QuestionType.REPUTATION,
            'investment': QuestionType.INVESTMENT,
            'regulation': QuestionType.REGULATION,
            'esg': QuestionType.ESG
        }
        
        selected_types = data.get('question_types', [])
        if selected_types:
            question_types = [type_mapping[t] for t in selected_types if t in type_mapping]
        
        use_inspiration = data.get('use_inspiration', True)
        max_questions_per_type = data.get('max_questions_per_type', 3)
        min_total_questions = data.get('min_total_questions', 30)
        
        # 在后台执行分析
        def run_analysis():
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            try:
                session_id = loop.run_until_complete(
                    analysis_system.analyze_enterprise(
                        enterprise_name=enterprise_name,
                        question_types=question_types,
                        use_inspiration=use_inspiration,
                        max_questions_per_type=max_questions_per_type,
                        min_total_questions=min_total_questions
                    )
                )
                return session_id
            finally:
                loop.close()
        
        # 使用线程池执行
        with concurrent.futures.ThreadPoolExecutor() as executor:
            future = executor.submit(run_analysis)
            session_id = future.result(timeout=300)  # 5分钟超时
        
        # 检查是否需要自动进行威胁分析
        config = load_config()
        if config.get('system_settings', {}).get('threat_analysis', {}).get('auto_analyze_new_sessions', False):
            try:
                # 在后台执行威胁分析
                def run_threat_analysis():
                    loop = asyncio.new_event_loop()
                    asyncio.set_event_loop(loop)
                    try:
                        result = loop.run_until_complete(
                            threat_system.analyze_session_threats(session_id)
                        )
                        return result
                    finally:
                        loop.close()
                
                # 使用线程池执行威胁分析
                with concurrent.futures.ThreadPoolExecutor() as executor:
                    future = executor.submit(run_threat_analysis)
                    threat_session_id = future.result(timeout=180)  # 3分钟超时
                
                return jsonify({
                    'success': True,
                    'session_id': session_id,
                    'threat_session_id': threat_session_id,
                    'message': f'企业 {enterprise_name} 分析和威胁分析已完成'
                })
            except Exception as e:
                print(f"❌ 自动威胁分析失败: {e}")
                # 即使威胁分析失败，也返回成功的企业分析结果
                return jsonify({
                    'success': True,
                    'session_id': session_id,
                    'message': f'企业 {enterprise_name} 分析已完成（威胁分析失败：{str(e)}）'
                })
        
        return jsonify({
            'success': True,
            'session_id': session_id,
            'message': f'企业 {enterprise_name} 分析已完成'
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/analysis/sessions', methods=['GET'])
def get_analysis_sessions():
    """获取分析会话列表"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 获取最近的分析会话
        limit = request.args.get('limit', 20, type=int)
        cursor.execute('''
            SELECT session_id, enterprise_name, created_at, completed_at, 
                   status, total_questions, successful_responses
            FROM analysis_sessions 
            ORDER BY created_at DESC 
            LIMIT ?
        ''', (limit,))
        
        sessions = []
        for row in cursor.fetchall():
            sessions.append({
                'session_id': row[0],
                'enterprise_name': row[1],
                'created_at': row[2],
                'completed_at': row[3],
                'status': row[4],
                'total_questions': row[5],
                'successful_responses': row[6]
            })
        
        conn.close()
        return jsonify({'success': True, 'sessions': sessions})
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/analysis/sessions/<session_id>', methods=['GET'])
def get_session_details(session_id):
    """获取会话详情"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 获取会话基本信息
        cursor.execute('''
            SELECT session_id, enterprise_name, created_at, status, total_questions, 
                   successful_responses, metadata
            FROM analysis_sessions 
            WHERE session_id = ?
        ''', (session_id,))
        
        session_row = cursor.fetchone()
        if not session_row:
            conn.close()
            return jsonify({'success': False, 'error': '会话不存在'}), 404
        
        # 获取问题和AI响应
        cursor.execute('''
            SELECT q.question_text, q.question_type, q.is_inspirational,
                   r.ai_provider, r.response_text, r.success, r.response_time, r.error_message
            FROM questions q
            LEFT JOIN ai_responses r ON q.id = r.question_id
            WHERE q.session_id = ?
            ORDER BY q.id, r.ai_provider
        ''', (session_id,))
        
        qa_data = cursor.fetchall()
        conn.close()
        
        # 组织数据结构
        session_info = {
            'session_id': session_row[0],
            'enterprise_name': session_row[1],
            'created_at': session_row[2],
            'status': session_row[3],
            'total_questions': session_row[4],
            'successful_responses': session_row[5],
            'metadata': session_row[6]
        }
        
        # 按问题分组响应
        questions_dict = {}
        for row in qa_data:
            question_text = row[0]
            question_type = row[1]
            is_inspirational = row[2]
            provider = row[3]
            response_text = row[4]
            success = row[5]
            response_time = row[6]
            error_message = row[7]
            
            if question_text not in questions_dict:
                questions_dict[question_text] = {
                    'question_text': question_text,
                    'question_type': question_type,
                    'is_inspirational': is_inspirational,
                    'responses': {}
                }
            
            if provider:
                questions_dict[question_text]['responses'][provider] = {
                    'text': response_text,
                    'success': success,
                    'response_time': response_time,
                    'error_message': error_message
                }
        
        questions_list = list(questions_dict.values())
        
        return jsonify({
            'success': True,
            'session': session_info,
            'questions': questions_list
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/analysis/sessions/<session_id>', methods=['DELETE'])
def delete_session(session_id):
    """删除分析会话"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 检查会话是否存在
        cursor.execute('SELECT session_id FROM analysis_sessions WHERE session_id = ?', (session_id,))
        if not cursor.fetchone():
            conn.close()
            return jsonify({'success': False, 'error': '会话不存在'}), 404
        
        # 删除相关数据（外键约束会自动删除相关记录）
        cursor.execute('DELETE FROM analysis_sessions WHERE session_id = ?', (session_id,))
        
        conn.commit()
        conn.close()
        
        return jsonify({
            'success': True,
            'message': '会话删除成功'
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/threat/analyze/<session_id>', methods=['POST'])
def analyze_threats(session_id):
    """执行威胁分析"""
    try:
        if not threat_system:
            return jsonify({'success': False, 'error': '威胁分析系统未初始化'}), 500
            
        # 检查DeepSeek API Key是否已配置
        if not api_key_manager.keys.get('deepseek', {}).get('api_key'):
            return jsonify({
                'success': False, 
                'error': '威胁分析需要配置DeepSeek API Key',
                'action_required': 'configure_deepseek'
            }), 400
        
        # 在后台执行威胁分析
        def run_threat_analysis():
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            try:
                result = loop.run_until_complete(
                    threat_system.analyze_session_threats(session_id)
                )
                return result
            finally:
                loop.close()
        
        # 使用线程池执行
        with concurrent.futures.ThreadPoolExecutor() as executor:
            future = executor.submit(run_threat_analysis)
            result = future.result(timeout=180)  # 3分钟超时
        
        return jsonify({
            'success': True,
            'threat_session_id': result,
            'message': '威胁分析已完成'
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/threat/sessions/<threat_session_id>', methods=['GET'])
def get_threat_details(threat_session_id):
    """获取威胁分析详情"""
    try:
        if not threat_system:
            return jsonify({'success': False, 'error': '威胁分析系统未初始化'}), 500
        
        details = threat_system.get_threat_session_details(threat_session_id)
        return jsonify({'success': True, 'details': details})
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/system/initialize', methods=['POST'])
def initialize_system():
    """初始化系统数据库"""
    try:
        initializer = DatabaseInitializer(DATABASE_PATH)
        initializer.initialize_database()
        
        # 重新初始化系统
        success = init_systems()
        
        return jsonify({
            'success': True,
            'message': '系统数据库初始化完成',
            'system_initialized': success
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/system/reinit', methods=['POST'])
def reinitialize_systems():
    """重新初始化分析系统"""
    try:
        success = init_systems()
        enabled_providers = api_key_manager.get_enabled_providers()
        
        return jsonify({
            'success': success,
            'message': '系统重新初始化完成' if success else '系统初始化失败',
            'systems': {
                'analysis': analysis_system is not None,
                'threat': threat_system is not None
            },
            'enabled_providers': enabled_providers,
            'provider_count': len(enabled_providers)
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/system/status', methods=['GET'])
def get_system_status():
    """获取系统详细状态"""
    try:
        enabled_providers = api_key_manager.get_enabled_providers()
        
        status = {
            'systems': {
                'analysis': analysis_system is not None,
                'threat': threat_system is not None,
                'database': os.path.exists(DATABASE_PATH)
            },
            'providers': {
                'enabled': enabled_providers,
                'total_configured': len([p for p in api_key_manager.keys.values() if p.get('api_key')]),
                'total_enabled': len(enabled_providers),
                'deepseek_configured': bool(api_key_manager.keys.get('deepseek', {}).get('api_key'))
            },
            'files': {
                'config_exists': os.path.exists(CONFIG_FILE),
                'api_keys_exists': os.path.exists(API_KEYS_FILE),
                'database_exists': os.path.exists(DATABASE_PATH)
            },
            'ready_for_analysis': analysis_system is not None and len(enabled_providers) > 0,
            'ready_for_threat_analysis': threat_system is not None and bool(api_key_manager.keys.get('deepseek', {}).get('api_key'))
        }
        
        return jsonify({
            'success': True,
            'status': status,
            'message': '系统状态检查完成'
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/reports', methods=['GET'])
def get_reports():
    """获取历史报告列表"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 获取分析会话作为报告
        cursor.execute('''
            SELECT 
                as_.session_id,
                as_.enterprise_name,
                as_.created_at,
                as_.status,
                as_.total_questions,
                COUNT(DISTINCT ar.ai_provider) as provider_count,
                tas.analysis_session_id,
                tas.threats_detected,
                0 as medium_risk_count,
                0 as low_risk_count
            FROM analysis_sessions as_
            LEFT JOIN ai_responses ar ON as_.session_id = ar.session_id
            LEFT JOIN threat_analysis_sessions tas ON as_.session_id = tas.original_session_id
            WHERE as_.status = 'completed'
            GROUP BY as_.session_id
            ORDER BY as_.created_at DESC
            LIMIT 100
        ''')
        
        reports = []
        for row in cursor.fetchall():
            reports.append({
                'id': row[0],
                'title': f"{row[1]} - 企业分析报告",
                'enterprise_name': row[1],
                'created_at': row[2],
                'status': row[3],
                'total_questions': row[4],
                'provider_count': row[5],
                'threat_session_id': row[6],
                'risk_summary': {
                    'high': row[7] or 0,
                    'medium': row[8] or 0,
                    'low': row[9] or 0
                },
                'type': 'enterprise_analysis'
            })
        
        conn.close()
        
        return jsonify({
            'success': True,
            'reports': reports
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/reports/<report_id>', methods=['GET'])
def get_report_details(report_id):
    """获取报告详情"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 获取分析会话详情
        cursor.execute('''
            SELECT session_id, enterprise_name, created_at, status, total_questions
            FROM analysis_sessions 
            WHERE session_id = ?
        ''', (report_id,))
        
        session_data = cursor.fetchone()
        if not session_data:
            return jsonify({'success': False, 'error': '报告不存在'}), 404
        
        # 获取问题和回答
        cursor.execute('''
            SELECT q.question_type, q.question_text, ar.ai_provider, ar.response_text, ar.response_time
            FROM questions q
            LEFT JOIN ai_responses ar ON q.id = ar.question_id
            WHERE q.session_id = ?
            ORDER BY q.question_type, ar.ai_provider
        ''', (report_id,))
        
        qa_data = cursor.fetchall()
        
        # 组织问答数据
        questions = {}
        for row in qa_data:
            q_type, q_text, provider, response, resp_time = row
            if q_type not in questions:
                questions[q_type] = {
                    'question': q_text,
                    'responses': {}
                }
            if provider and response:
                questions[q_type]['responses'][provider] = {
                    'text': response,
                    'response_time': resp_time
                }
        
        # 获取威胁分析（如果有）
        cursor.execute('''
            SELECT analysis_session_id, threats_detected, 0 as medium_risk_count, 0 as low_risk_count
            FROM threat_analysis_sessions
            WHERE original_session_id = ?
        ''', (report_id,))
        
        threat_data = cursor.fetchone()
        
        conn.close()
        
        report_details = {
            'session_id': session_data[0],
            'enterprise_name': session_data[1],
            'created_at': session_data[2],
            'status': session_data[3],
            'total_questions': session_data[4],
            'questions': questions,
            'threat_analysis': {
                'threat_session_id': threat_data[0] if threat_data else None,
                'risk_counts': {
                    'high': threat_data[1] if threat_data else 0,
                    'medium': threat_data[2] if threat_data else 0,
                    'low': threat_data[3] if threat_data else 0
                }
            } if threat_data else None
        }
        
        return jsonify({
            'success': True,
            'report': report_details
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/threats', methods=['GET'])
def get_threat_analysis_list():
    """获取威胁分析列表"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 获取威胁分析会话列表
        limit = request.args.get('limit', 20, type=int)
        cursor.execute('''
            SELECT tas.analysis_session_id, tas.original_session_id, tas.enterprise_name,
                   tas.total_responses, tas.threats_detected, tas.avg_threat_score,
                   tas.highest_threat_level, tas.analysis_started_at, tas.analysis_completed_at,
                   tas.status
            FROM threat_analysis_sessions tas
            ORDER BY tas.analysis_started_at DESC
            LIMIT ?
        ''', (limit,))
        
        threat_sessions = []
        for row in cursor.fetchall():
            threat_sessions.append({
                'analysis_session_id': row[0],
                'original_session_id': row[1],
                'enterprise_name': row[2],
                'total_responses': row[3],
                'threats_detected': row[4],
                'avg_threat_score': round(row[5], 2) if row[5] else 0,
                'highest_threat_level': row[6],
                'analysis_started_at': row[7],
                'analysis_completed_at': row[8],
                'status': row[9]
            })
        
        conn.close()
        return jsonify({'success': True, 'threat_sessions': threat_sessions})
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/threats/<analysis_session_id>', methods=['GET'])
def get_threat_analysis_details(analysis_session_id):
    """获取威胁分析详情"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 获取威胁分析会话信息
        cursor.execute('''
            SELECT tas.analysis_session_id, tas.original_session_id, tas.enterprise_name,
                   tas.total_responses, tas.threats_detected, tas.avg_threat_score,
                   tas.highest_threat_level, tas.analysis_started_at, tas.analysis_completed_at,
                   tas.status, tas.metadata
            FROM threat_analysis_sessions tas
            WHERE tas.analysis_session_id = ?
        ''', (analysis_session_id,))
        
        session_row = cursor.fetchone()
        if not session_row:
            return jsonify({'success': False, 'error': '威胁分析会话不存在'}), 404
        
        session_info = {
            'analysis_session_id': session_row[0],
            'original_session_id': session_row[1],
            'enterprise_name': session_row[2],
            'total_responses': session_row[3],
            'threats_detected': session_row[4],
            'avg_threat_score': round(session_row[5], 2) if session_row[5] else 0,
            'highest_threat_level': session_row[6],
            'analysis_started_at': session_row[7],
            'analysis_completed_at': session_row[8],
            'status': session_row[9],
            'metadata': json.loads(session_row[10]) if session_row[10] else {}
        }
        
        # 获取详细的威胁分析结果（使用原始会话ID）
        cursor.execute('''
            SELECT ta.id, ta.question_text, ta.ai_provider, ta.ai_response,
                   ta.threat_detected, ta.threat_types, ta.threat_level, ta.threat_score,
                   ta.threat_description, ta.recommended_actions, ta.confidence_score,
                   ta.analysis_details, ta.analyzed_at
            FROM threat_analysis ta
            WHERE ta.session_id = ?
            ORDER BY ta.threat_score DESC, ta.analyzed_at ASC
        ''', (session_info['original_session_id'],))
        
        threat_details = []
        for row in cursor.fetchall():
            threat_details.append({
                'id': row[0],
                'question_text': row[1],
                'ai_provider': row[2],
                'ai_response': row[3],
                'threat_detected': bool(row[4]),
                'threat_types': json.loads(row[5]) if row[5] else [],
                'threat_level': row[6],
                'threat_score': round(row[7], 2),
                'threat_description': row[8],
                'recommended_actions': json.loads(row[9]) if row[9] else [],
                'confidence_score': round(row[10], 2),
                'analysis_details': json.loads(row[11]) if row[11] else {},
                'analyzed_at': row[12]
            })
        
        # 获取统计信息（使用原始会话ID）
        cursor.execute('''
            SELECT 
                COUNT(*) as total_analyzed,
                SUM(CASE WHEN threat_detected THEN 1 ELSE 0 END) as total_threats,
                COUNT(CASE WHEN threat_level = 'critical' THEN 1 END) as critical_count,
                COUNT(CASE WHEN threat_level = 'high' THEN 1 END) as high_count,
                COUNT(CASE WHEN threat_level = 'medium' THEN 1 END) as medium_count,
                COUNT(CASE WHEN threat_level = 'low' THEN 1 END) as low_count,
                AVG(threat_score) as avg_score,
                MAX(threat_score) as max_score,
                AVG(confidence_score) as avg_confidence
            FROM threat_analysis
            WHERE session_id = ?
        ''', (session_info['original_session_id'],))
        
        stats_row = cursor.fetchone()
        statistics = {
            'total_analyzed': stats_row[0],
            'total_threats': stats_row[1],
            'critical_count': stats_row[2],
            'high_count': stats_row[3],
            'medium_count': stats_row[4],
            'low_count': stats_row[5],
            'avg_score': round(stats_row[6], 2) if stats_row[6] else 0,
            'max_score': round(stats_row[7], 2) if stats_row[7] else 0,
            'avg_confidence': round(stats_row[8], 2) if stats_row[8] else 0
        }
        
        conn.close()
        return jsonify({
            'success': True, 
            'session_info': session_info,
            'threat_details': threat_details,
            'statistics': statistics
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/threats/statistics', methods=['GET'])
def get_threat_statistics():
    """获取威胁分析统计数据"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 总体统计
        cursor.execute('''
            SELECT 
                COUNT(DISTINCT tas.analysis_session_id) as total_sessions,
                COUNT(DISTINCT s.enterprise_name) as total_enterprises,
                COUNT(DISTINCT t.id) as total_threats,
                AVG(t.threat_score) as overall_avg_score
            FROM threat_analysis_sessions tas
            LEFT JOIN analysis_sessions s ON tas.original_session_id = s.session_id
            LEFT JOIN threat_analysis t ON t.session_id = s.session_id
            WHERE tas.status = 'completed'
        ''')
        
        overall_stats = cursor.fetchone()
        
        # 威胁等级分布
        cursor.execute('''
            SELECT threat_level, COUNT(*) as count
            FROM threat_analysis
            WHERE threat_detected = 1
            GROUP BY threat_level
        ''')
        
        threat_level_distribution = {}
        for row in cursor.fetchall():
            if row[0]:
                threat_level_distribution[row[0]] = row[1]
        
        # 企业风险排名
        cursor.execute('''
            SELECT s.enterprise_name, 
                   COUNT(*) as session_count,
                   COUNT(CASE WHEN t.threat_detected = 1 THEN 1 END) as total_threats,
                   AVG(t.threat_score) as avg_score,
                   MAX(t.threat_level) as max_level
            FROM threat_analysis t
            JOIN analysis_sessions s ON t.session_id = s.session_id
            GROUP BY s.enterprise_name
            HAVING session_count > 0
            ORDER BY avg_score DESC
            LIMIT 10
        ''')
        
        enterprise_rankings = []
        for row in cursor.fetchall():
            enterprise_rankings.append({
                'enterprise_name': row[0],
                'session_count': row[1],
                'total_threats': row[2],
                'avg_score': round(row[3], 2) if row[3] else 0,
                'max_level': row[4]
            })
        
        # 最近7天趋势
        cursor.execute('''
            SELECT DATE(t.analyzed_at) as date,
                   COUNT(*) as sessions,
                   COUNT(CASE WHEN t.threat_detected = 1 THEN 1 END) as threats
            FROM threat_analysis t
            WHERE t.analyzed_at >= datetime('now', '-7 days')
            GROUP BY DATE(t.analyzed_at)
            ORDER BY date
        ''')
        
        recent_trends = []
        for row in cursor.fetchall():
            recent_trends.append({
                'date': row[0],
                'sessions': row[1],
                'threats': row[2]
            })
        
        conn.close()
        return jsonify({
            'success': True,
            'overall_stats': {
                'total_sessions': overall_stats[0] or 0,
                'total_enterprises': overall_stats[1] or 0, 
                'total_threats': overall_stats[2] or 0,
                'overall_avg_score': round(overall_stats[3], 2) if overall_stats[3] else 0
            },
            'threat_level_distribution': threat_level_distribution,
            'enterprise_rankings': enterprise_rankings,
            'recent_trends': recent_trends
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/projects', methods=['GET'])
def get_projects():
    """获取项目列表"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 按企业名称分组统计项目
        cursor.execute('''
            SELECT 
                enterprise_name,
                COUNT(*) as session_count,
                MAX(created_at) as last_activity,
                SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_count,
                SUM(total_questions) as total_questions
            FROM analysis_sessions
            GROUP BY enterprise_name
            ORDER BY last_activity DESC
        ''')
        
        projects = []
        for row in cursor.fetchall():
            enterprise_name, session_count, last_activity, completed_count, total_questions = row
            
            # 获取该企业的威胁分析统计
            cursor.execute('''
                SELECT 
                    COUNT(*) as threat_sessions,
                    SUM(threats_detected) as total_high_risk,
                    0 as total_medium_risk,
                    0 as total_low_risk
                FROM threat_analysis_sessions tas
                JOIN analysis_sessions as_ ON tas.original_session_id = as_.session_id
                WHERE as_.enterprise_name = ?
            ''', (enterprise_name,))
            
            threat_stats = cursor.fetchone()
            
            projects.append({
                'id': enterprise_name.replace(' ', '_').lower(),
                'name': enterprise_name,
                'description': f"{enterprise_name}企业舆情监控项目",
                'session_count': session_count,
                'completed_count': completed_count,
                'total_questions': total_questions or 0,
                'last_activity': last_activity,
                'threat_stats': {
                    'threat_sessions': threat_stats[0] or 0,
                    'high_risk': threat_stats[1] or 0,
                    'medium_risk': threat_stats[2] or 0,
                    'low_risk': threat_stats[3] or 0
                },
                'status': 'active' if session_count > 0 else 'inactive'
            })
        
        conn.close()
        
        return jsonify({
            'success': True,
            'projects': projects
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/projects/<project_id>', methods=['GET'])
def get_project_details(project_id):
    """获取项目详情"""
    try:
        # 将project_id转换回企业名称
        enterprise_name = project_id.replace('_', ' ').title()
        
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 获取该企业的所有分析会话
        cursor.execute('''
            SELECT session_id, created_at, status, total_questions
            FROM analysis_sessions
            WHERE enterprise_name LIKE ?
            ORDER BY created_at DESC
        ''', (f'%{enterprise_name}%',))
        
        sessions = []
        for row in cursor.fetchall():
            sessions.append({
                'session_id': row[0],
                'created_at': row[1],
                'status': row[2],
                'total_questions': row[3]
            })
        
        if not sessions:
            return jsonify({'success': False, 'error': '项目不存在'}), 404
        
        # 获取威胁分析统计
        cursor.execute('''
            SELECT 
                tas.analysis_session_id,
                tas.analysis_started_at,
                tas.threats_detected,
                0 as medium_risk_count,
                0 as low_risk_count
            FROM threat_analysis_sessions tas
            JOIN analysis_sessions as_ ON tas.original_session_id = as_.session_id
            WHERE as_.enterprise_name LIKE ?
            ORDER BY tas.analysis_started_at DESC
        ''', (f'%{enterprise_name}%',))
        
        threat_sessions = []
        for row in cursor.fetchall():
            threat_sessions.append({
                'analysis_session_id': row[0],
                'analysis_started_at': row[1],
                'threats_detected': row[2],
                'medium_risk_count': row[3],
                'low_risk_count': row[4]
            })
        
        conn.close()
        
        return jsonify({
            'success': True,
            'project': {
                'id': project_id,
                'name': enterprise_name,
                'sessions': sessions,
                'threat_sessions': threat_sessions
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/dashboard/stats', methods=['GET'])
def get_dashboard_stats():
    """获取仪表板统计数据"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 基础统计
        stats = {}
        
        # 企业总数
        cursor.execute('SELECT COUNT(DISTINCT enterprise_name) FROM analysis_sessions')
        stats['total_enterprises'] = cursor.fetchone()[0]
        
        # 分析会话总数
        cursor.execute('SELECT COUNT(*) FROM analysis_sessions')
        stats['total_sessions'] = cursor.fetchone()[0]
        
        # 完成的分析数
        cursor.execute('SELECT COUNT(*) FROM analysis_sessions WHERE status = "completed"')
        stats['completed_sessions'] = cursor.fetchone()[0]
        
        # 威胁分析总数
        cursor.execute('SELECT COUNT(*) FROM threat_analysis_sessions')
        stats['threat_sessions'] = cursor.fetchone()[0]
        
        # 添加兼容性字段
        stats['successful_responses'] = stats['completed_sessions']
        stats['total_responses'] = stats['total_sessions']
        
        # 最近7天的分析数量
        cursor.execute('''
            SELECT DATE(created_at) as date, COUNT(*) as count
            FROM analysis_sessions
            WHERE created_at >= datetime('now', '-7 days')
            GROUP BY DATE(created_at)
            ORDER BY date
        ''')
        daily_analysis = [{'date': row[0], 'count': row[1]} for row in cursor.fetchall()]
        
        # 威胁等级分布
        cursor.execute('''
            SELECT threat_level, COUNT(*) as count
            FROM threat_analysis 
            WHERE threat_level IS NOT NULL
            GROUP BY threat_level
        ''')
        threat_distribution = [{'level': row[0], 'count': row[1]} for row in cursor.fetchall()]
        
        conn.close()
        
        return jsonify({
            'success': True,
            'stats': stats,
            'daily_analysis': daily_analysis,
            'threat_distribution': threat_distribution
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/dashboard/recent', methods=['GET'])
def get_recent_activity():
    """获取最近活动"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 最近的分析会话
        cursor.execute('''
            SELECT session_id, enterprise_name, created_at, status, total_questions
            FROM analysis_sessions 
            ORDER BY created_at DESC 
            LIMIT 10
        ''')
        recent_sessions = []
        for row in cursor.fetchall():
            recent_sessions.append({
                'session_id': row[0],
                'enterprise_name': row[1],
                'created_at': row[2],
                'status': row[3],
                'total_questions': row[4]
            })
        
        # 最近的威胁分析
        cursor.execute('''
            SELECT tas.analysis_session_id, tas.original_session_id, 
                   as_.enterprise_name, tas.analysis_started_at, tas.threats_detected
            FROM threat_analysis_sessions tas
            JOIN analysis_sessions as_ ON tas.original_session_id = as_.session_id
            ORDER BY tas.analysis_started_at DESC 
            LIMIT 10
        ''')
        recent_threats = []
        for row in cursor.fetchall():
            recent_threats.append({
                'threat_session_id': row[0],
                'source_session_id': row[1],
                'enterprise_name': row[2],
                'created_at': row[3],
                'high_risk_count': row[4]
            })
        
        conn.close()
        
        return jsonify({
            'success': True,
            'recent_sessions': recent_sessions,
            'recent_threats': recent_threats
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/bigscreen/overview', methods=['GET'])
def get_bigscreen_overview():
    """大屏概览数据 - 专用API"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 基础统计
        cursor.execute('''
            SELECT 
                COUNT(DISTINCT enterprise_name) as total_enterprises,
                COUNT(*) as total_sessions,
                COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_sessions,
                AVG(total_questions) as avg_questions
            FROM analysis_sessions
        ''')
        
        basic_stats = cursor.fetchone()
        
        # 威胁统计
        cursor.execute('''
            SELECT 
                COUNT(*) as threat_sessions,
                COALESCE(SUM(threats_detected), 0) as total_threats,
                COALESCE(AVG(avg_threat_score), 0) as avg_threat_score
            FROM threat_analysis_sessions
        ''')
        
        threat_stats = cursor.fetchone()
        
        # AI响应统计
        cursor.execute('''
            SELECT 
                COUNT(*) as total_responses,
                COUNT(CASE WHEN success = 1 THEN 1 END) as successful_responses
            FROM ai_responses
        ''')
        
        ai_stats = cursor.fetchone()
        
        # 计算成功率
        total_responses = ai_stats[0] if ai_stats[0] else 1
        successful_responses = ai_stats[1] if ai_stats[1] else 0
        success_rate = round((successful_responses / total_responses) * 100, 2)
        
        # 近7天趋势
        cursor.execute('''
            SELECT 
                DATE(created_at) as date,
                COUNT(*) as count
            FROM analysis_sessions
            WHERE created_at >= datetime('now', '-7 days')
            GROUP BY DATE(created_at)
            ORDER BY date
        ''')
        
        daily_trend = [{'date': row[0], 'count': row[1]} for row in cursor.fetchall()]
        
        conn.close()
        
        overview_data = {
            'basic_stats': {
                'total_enterprises': basic_stats[0] if basic_stats else 0,
                'total_sessions': basic_stats[1] if basic_stats else 0,
                'completed_sessions': basic_stats[2] if basic_stats else 0,
                'avg_questions': round(basic_stats[3], 1) if basic_stats and basic_stats[3] else 0
            },
            'threat_stats': {
                'threat_sessions': threat_stats[0] if threat_stats else 0,
                'total_threats': threat_stats[1] if threat_stats else 0,
                'avg_threat_score': round(threat_stats[2], 2) if threat_stats and threat_stats[2] else 0
            },
            'system_health': {
                'success_rate': success_rate,
                'total_responses': total_responses,
                'successful_responses': successful_responses
            },
            'daily_trend': daily_trend
        }
        
        return jsonify({
            'success': True,
            'data': overview_data,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/bigscreen/threat-distribution', methods=['GET'])
def get_bigscreen_threat_distribution():
    """大屏威胁分布数据"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 威胁等级分布
        cursor.execute('''
            SELECT 
                threat_level,
                COUNT(*) as count
            FROM threat_analysis
            WHERE threat_detected = 1
            GROUP BY threat_level
        ''')
        
        level_distribution = {}
        for row in cursor.fetchall():
            level_distribution[row[0]] = row[1]
        
        # 威胁类型分布
        cursor.execute('''
            SELECT threat_types
            FROM threat_analysis
            WHERE threat_detected = 1 AND threat_types IS NOT NULL
        ''')
        
        type_counts = {}
        for row in cursor.fetchall():
            try:
                types = json.loads(row[0])
                for threat_type in types:
                    type_counts[threat_type] = type_counts.get(threat_type, 0) + 1
            except:
                continue
        
        # 企业威胁排名（通过会话关联）
        cursor.execute('''
            SELECT 
                as_.enterprise_name,
                COUNT(ta.id) as threat_count,
                AVG(ta.threat_score) as avg_score
            FROM threat_analysis ta
            JOIN analysis_sessions as_ ON ta.session_id = as_.session_id
            WHERE ta.threat_detected = 1
            GROUP BY as_.enterprise_name
            ORDER BY avg_score DESC
            LIMIT 10
        ''')
        
        enterprise_rankings = []
        for row in cursor.fetchall():
            enterprise_rankings.append({
                'enterprise_name': row[0],
                'threat_count': row[1],
                'avg_score': round(row[2], 2)
            })
        
        conn.close()
        
        return jsonify({
            'success': True,
            'data': {
                'level_distribution': level_distribution,
                'type_distribution': type_counts,
                'enterprise_rankings': enterprise_rankings
            },
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/bigscreen/recent-activity', methods=['GET'])
def get_bigscreen_recent_activity():
    """大屏最近活动数据"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 最近分析会话
        cursor.execute('''
            SELECT 
                session_id,
                enterprise_name,
                created_at,
                status,
                total_questions
            FROM analysis_sessions
            ORDER BY created_at DESC
            LIMIT 15
        ''')
        
        recent_sessions = []
        for row in cursor.fetchall():
            recent_sessions.append({
                'session_id': row[0],
                'enterprise_name': row[1],
                'created_at': row[2],
                'status': row[3],
                'total_questions': row[4]
            })
        
        # 最近威胁分析
        cursor.execute('''
            SELECT 
                tas.analysis_session_id,
                tas.enterprise_name,
                tas.analysis_started_at,
                tas.threats_detected,
                tas.highest_threat_level
            FROM threat_analysis_sessions tas
            ORDER BY tas.analysis_started_at DESC
            LIMIT 10
        ''')
        
        recent_threat_sessions = []
        for row in cursor.fetchall():
            recent_threat_sessions.append({
                'analysis_session_id': row[0],
                'enterprise_name': row[1],
                'analysis_started_at': row[2],
                'threats_detected': row[3],
                'highest_threat_level': row[4]
            })
        
        # 活动时间分布（24小时）
        cursor.execute('''
            SELECT 
                strftime('%H', created_at) as hour,
                COUNT(*) as count
            FROM analysis_sessions
            WHERE created_at >= datetime('now', '-1 day')
            GROUP BY strftime('%H', created_at)
            ORDER BY hour
        ''')
        
        hourly_activity = []
        activity_map = {row[0]: row[1] for row in cursor.fetchall()}
        for hour in range(24):
            hour_str = f"{hour:02d}"
            hourly_activity.append({
                'hour': hour_str,
                'count': activity_map.get(hour_str, 0)
            })
        
        conn.close()
        
        return jsonify({
            'success': True,
            'data': {
                'recent_sessions': recent_sessions,
                'recent_threat_sessions': recent_threat_sessions,
                'hourly_activity': hourly_activity
            },
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/bigscreen/system-monitor', methods=['GET'])
def get_bigscreen_system_monitor():
    """大屏系统监控数据"""
    try:
        # 检查系统状态
        status_info = {
            'database': True,
            'analysis_system': analysis_system is not None,
            'threat_system': threat_system is not None,
            'ai_providers': []
        }
        
        # 检查AI提供商状态
        if analysis_system:
            config = analysis_system.get_current_config()
            for provider_name, provider_config in config.get('ai_providers', {}).items():
                if provider_config.get('enabled', False):
                    status_info['ai_providers'].append({
                        'name': provider_name,
                        'enabled': True,
                        'has_api_key': bool(provider_config.get('api_key')),
                        'status': 'active' if provider_config.get('api_key') else 'inactive'
                    })
        
        # 数据库连接测试
        try:
            conn = sqlite3.connect(DATABASE_PATH)
            cursor = conn.cursor()
            cursor.execute('SELECT 1')
            conn.close()
            status_info['database'] = True
        except:
            status_info['database'] = False
        
        # 性能指标（近1小时）
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()
        
        # 响应时间统计
        cursor.execute('''
            SELECT 
                AVG(response_time) as avg_response_time,
                MAX(response_time) as max_response_time,
                COUNT(*) as total_requests
            FROM ai_responses
            WHERE created_at >= datetime('now', '-1 hour')
        ''')
        
        perf_data = cursor.fetchone()
        
        # 错误率
        cursor.execute('''
            SELECT 
                COUNT(CASE WHEN success = 0 THEN 1 END) as error_count,
                COUNT(*) as total_count
            FROM ai_responses
            WHERE created_at >= datetime('now', '-1 hour')
        ''')
        
        error_data = cursor.fetchone()
        error_rate = 0
        if error_data and error_data[1] > 0:
            error_rate = round((error_data[0] / error_data[1]) * 100, 2)
        
        conn.close()
        
        performance_metrics = {
            'avg_response_time': round(perf_data[0], 2) if perf_data and perf_data[0] else 0,
            'max_response_time': round(perf_data[1], 2) if perf_data and perf_data[1] else 0,
            'total_requests': perf_data[2] if perf_data else 0,
            'error_rate': error_rate,
            'uptime': '99.9%'  # 简化的正常运行时间
        }
        
        return jsonify({
            'success': True,
            'data': {
                'system_status': status_info,
                'performance_metrics': performance_metrics,
                'health_score': 100 - error_rate
            },
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/bigscreen/provider-status', methods=['GET'])
def get_bigscreen_provider_status():
    """大屏AI服务提供商状态"""
    try:
        provider_status = {}
        
        # 直接读取API keys配置文件
        try:
            with open(API_KEYS_FILE, 'r', encoding='utf-8') as f:
                api_config = json.load(f)
        except FileNotFoundError:
            api_config = {}
        
        # 处理所有配置的提供商
        for provider_name, provider_config in api_config.items():
            api_key = provider_config.get('api_key', '').strip()
            enabled = provider_config.get('enabled', False)
            
            # 检查API key有效性
            has_key = bool(api_key)
            key_valid = has_key and len(api_key) > 10 and not api_key.startswith('your_') and api_key != 'sk-xxx'
            
            # 确定状态
            if enabled and key_valid:
                status = 'active'
                status_text = '正常运行'
                color = '#16a34a'
            elif has_key and not enabled:
                status = 'disabled'
                status_text = '已禁用'
                color = '#ea580c'
            elif enabled and not key_valid:
                status = 'error'
                status_text = 'API密钥无效'
                color = '#dc2626'
            else:
                status = 'inactive'
                status_text = '未配置'
                color = '#666'
            
            # 只显示有API key的提供商，或者所有配置项（即使为空）
            provider_status[provider_name] = {
                'name': provider_name,
                'enabled': enabled,
                'has_api_key': has_key,
                'key_valid': key_valid,
                'status': status,
                'status_text': status_text,
                'color': color,
                'api_key_length': len(api_key) if api_key else 0
            }
        
        # 如果没有任何配置的提供商
        if not provider_status:
            return jsonify({
                'success': True,
                'data': {
                    'providers': {},
                    'summary': {
                        'total_providers': 0,
                        'active_providers': 0,
                        'configured_providers': 0,
                        'health_percentage': 0,
                        'message': '暂无AI服务提供商配置'
                    }
                },
                'timestamp': datetime.now().isoformat()
            })
        
        # 统计各种状态的提供商
        active_count = sum(1 for p in provider_status.values() if p['status'] == 'active')
        configured_count = sum(1 for p in provider_status.values() if p['has_api_key'])
        total_count = len(provider_status)
        
        return jsonify({
            'success': True,
            'data': {
                'providers': provider_status,
                'summary': {
                    'total_providers': total_count,
                    'active_providers': active_count,
                    'configured_providers': configured_count,
                    'health_percentage': round((active_count / total_count) * 100, 1) if total_count > 0 else 0,
                    'message': f'共 {total_count} 个提供商，{configured_count} 个已配置，{active_count} 个活跃'
                }
            },
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

# 静态文件服务
@app.route('/')
def index():
    """主页"""
    return send_from_directory('web', 'index.html')

@app.route('/<path:filename>')
def static_files(filename):
    """静态文件"""
    return send_from_directory('web', filename)

if __name__ == '__main__':
    # 初始化系统
    init_systems()
    
    # 启动Flask应用
    print("🚀 企业舆情分析系统后端服务启动...")
    print("📱 Web界面: http://localhost:5000")
    print("🔗 API文档: http://localhost:5000/api/health")
    
    app.run(host='0.0.0.0', port=5000, debug=True, threaded=True) 